package org.benjamin.wechat.controller;

import java.io.IOException;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.benjamin.wechat.domain.WechatMessage;
import org.benjamin.wechat.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

@Controller
@RequestMapping
public class HomeController {
	
	private Logger logger = LogManager.getLogger();
	
	@Autowired
	private UserInfoService userInfoService;

    @RequestMapping(value = {"index",""})
    public ModelAndView index(){
        return new ModelAndView("home.index");
    }
    
    @ResponseBody
    @PostMapping(value = "api/request")
    public String apiRequest(HttpServletRequest request, @RequestBody String body) {
    	XmlMapper xmlMapper = new XmlMapper();
    	logger.info(request.getMethod());
    	xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    	xmlMapper.setSerializationInclusion(Include.NON_NULL);
    	try {
    		if(StringUtils.isNotBlank(body)) {
    			logger.info(body);
    			WechatMessage message = null;
    			message = xmlMapper.readValue(body, WechatMessage.class);
    			if(message.getMsgType().equals("event")) {
    				if(message.getEvent().equals("subscribe")) {
    					logger.info("当前用户{},订阅成功！开发者编号{}",message.getFromUserName(),message.getToUserName());
    					this.userInfoService.subscribeUser(message.getFromUserName(), message.getToUserName());
    					return "您已经订阅成功";
    				}
    			}
    		}
		} catch (IOException e) {
			e.printStackTrace();
		}
    	return "";
    }
    
    @ResponseBody
    @GetMapping(value = "api/request")
    public String signatureRequest(@RequestParam("signature")String signature,
    		@RequestParam("timestamp") Long timestamp,@RequestParam("nonce")Long nonce,
    		@RequestParam("echostr")String echostr) {
    	try {
    		String token = "echo";
        	logger.info("微信对接校验");
        	String[] temps = {token,timestamp.toString(),nonce.toString()};
    		Arrays.sort(temps);
    		StringBuffer buffer = new StringBuffer();
    		for(int i = 0;i< temps.length;i++) {
    			String temp = temps[i];
    			buffer.append(temp);
    		}
    		logger.debug("参数进行SHA1加密");
    		String outSig = DigestUtils.sha1Hex(buffer.toString());
    		if(outSig.equals(signature)) {
    			logger.debug("微信系统对接，SHA1加密匹配成功");
    			return echostr;	
    		}
    	}catch(Exception ex) {
    		logger.error(ex.getMessage(),ex);
    	}
		logger.warn("微信系统对接失败");
		return "";
    }

}
